<?php 
// 广告管理
namespace Admin\Model;
use Think\Model;
class AdvertisementModel extends Model {
	 protected $tableName = 'advertisement';
	  protected $_validate = array(
		array('ad_name','require','广告名不能为空！'), 
		array('ad_name','','广告名称已经存在！',0,'unique',1),
		array('account','/^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$/','必须大于0',0,'regex',3),   
		
     ); 

	// 上架状态不能修改广告主名，广告，广告类型，上架时间
	public function adData($ad_id='',$data)	
	{
		$shelf_status=$this->where(['id'=>$ad_id])->getField('shelf_status');
		if ($shelf_status=='1') {
			// unset($data['ad_name']);
			unset($data['advertiser_id']);
			// unset($data['ad_type']);
			unset($data['shelf_time']);
		}

		return $data;		 
	}
	// 广告主上架 生成上架数据
	public function createOnData($ad_id='')
	{
		$shelf_status=$this->where(['id'=>$ad_id])->getField('shelf_status');

		if ($shelf_status=='0') {
			 return false;
		}

		$shelf_time=$this->where(['id'=>$ad_id])->getField('shelf_time');

	 	$daydiff= timediff(time(),$shelf_time);//相差天数
 		
		for ($i=0,$add_time=$shelf_time; $i < $daydiff ; $i++) {  
			$data[$i]=$this->createOneData($ad_id);
			$data[$i]['add_time']=$add_time;
			$add_time+=86400; 	
		}	 

		$data=array_values($data);
		$res=M('advertiser_data')->addAll($data);
		
		return $res ? true : false;		
	}

	// 生成一条数据
	public function createOneData($ad_id='')
	{
		if (C('IS_FALSE_DEL')) {
        	$where['a.is_delete']='0';	 
        	$where['b.is_delete']='0';	 
        }else{
        	$where=[];
        }

        $where['a.id']=$ad_id;

		$data=M('advertisement a')
		->join('wm_advertiser b on a.advertiser_id=b.id')
		->field('a.id as ad_id,a.ad_name,a.advertiser_id as adv_id,b.company_name as adv_name,a.access_unit_price,a.cooperation_type')
		->where($where)
		->find();

		return $data;
		// $res=M('advertiser_data')->add($data);
	}
	// 生成下架数据
	public function createOffData($ad_id='')
	{
		$shelf_status=$this->where(['id'=>$ad_id])->getField('shelf_status');
		
		if ($shelf_status=='1') {
			 return false;
		}

		$data=$this->createOneData($ad_id);
		$data['add_time']=time();
		$res=M('advertiser_data')->add($data);

		return $res ? true : false;

	}
	//验证广告上架 
	
	public function checkAdOnShelf($ad_id,$shelf_status='')
	{
		// 下架时间
		$off_shelf_time=$this->where(['id'=>$ad_id])->getField('off_shelf_time');

		$shelf_time=$this->where(['id'=>$ad_id])->getField('shelf_time');

		if ($shelf_status=='0') {
			 return true;
		} 

		if (($shelf_time-$off_shelf_time>86400)&&($shelf_time<=time())) {
			 return true;
		}else{
			return false;
		}

	}
	// 验证上下架状态防止重复上下架
	public function checkShelfStatus($ad_id,$shelf_status)
	{
		$shelf_status1=$this->where(['id'=>$ad_id])->getField('shelf_status');
		if ($shelf_status==(int)$shelf_status1) {
			return false;
		}else{
			return true;
		}
	}
    	 
}